package com.yumo.kangchenjunga.customer;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yumo.kangchenjunga.activity.NoSuchActivityException;
import com.yumo.kangchenjunga.coupon.v1.CouponCustomerSummaryVo;
import com.yumo.kangchenjunga.coupon.v1.NoMoreAllocatedCouponException;
import com.yumo.kangchenjunga.coupon.v1.ObtainVo;
import com.yumo.kangchenjunga.exception.controller.HttpBadRequestException;
import com.yumo.kangchenjunga.exception.controller.HttpNotFoundException;

@RestController
@RequestMapping("/api/v1")
public final class CustomerController {

	@Autowired
	private CustomerService service;

	@PostMapping("/bindings/{systemId}/{invitationCode}")
	public String bind(@PathVariable String systemId, @PathVariable String invitationCode) {
		return "true";
	}

	@GetMapping("/customers/{id}")
	public Customer queryById(@PathVariable int id) throws HttpNotFoundException {
		try {
			return service.queryById(id);
		} catch (NoSuchCustomerException e) {
			throw HttpNotFoundException.build(e, "信托客户 [ id: %d ] 不存在。", id);
		}
	}

	@PostMapping("/customers/service/query")
	public Page<CustomerVo> query(@RequestBody CustomerVo customer,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		return service.query(customer, pageable);
	}

	@GetMapping("/customers/")
	public Iterable<Customer> list() {
		return service.list();
	}

	@GetMapping(path = "/customers/", params = { "paged" })
	public Page<Customer> page(
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		return service.page(pageable);
	}

	@PostMapping("/customers/")
	public Customer create(@RequestBody Customer customer) {
		return service.create(customer);
	}

	@DeleteMapping("/customers/{id}")
	public void delete(@PathVariable int id) {
		service.delete(id);
	}

	@PutMapping("/customers/{id}")
	public Customer modify(@PathVariable int id, @RequestBody Customer customer)
			throws HttpNotFoundException, HttpBadRequestException {
		if (id == customer.getId()) {
			try {
				return service.modify(id, customer);
			} catch (NoSuchCustomerException e) {
				throw HttpNotFoundException.build(e, "信托客户 [ id: %d ] 不存在。", id);
			}
		}

		throw HttpBadRequestException.build("The id in the path(%d) and body(%d) does not match.", id,
				customer.getId());
	}

	@GetMapping("/customers/{customerId}/coupons/summary")
	public CouponCustomerSummaryVo getCouponSummary(@PathVariable int customerId) {
		return service.getCouponSummary(customerId);
	}

	@PostMapping("/customers/{customerId}/coupons/obtain/{activityId}")
	public ObtainVo obtain(@PathVariable int customerId, @PathVariable int activityId) throws HttpNotFoundException {
		try {
			return service.obtain(customerId, activityId);
		} catch (NoMoreAllocatedCouponException e) {
			throw HttpNotFoundException.build(e, "暂时没有可以领取的优惠券。");
		} catch (NoSuchActivityException e) {
			throw HttpNotFoundException.build(e, "权益 [ id: %d ] 不存在。", activityId);
		}
	}

	@ExceptionHandler(Exception.class)
	public void handler(Exception e, HttpServletResponse response) throws IOException {
		if (e instanceof DataIntegrityViolationException) {
			response.sendError(400, "客户号或手机号重复。");
		} else if (e instanceof IllegalArgumentException) {
			response.sendError(400, e.getMessage());
		} else {
			response.sendError(500);
		}
	}

}
